package src.ee.ioc.smaug.parser;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

import src.ee.ioc.smaug.world.evolution.EnvDescription;

public class Transform {
    private static void transformFile(String from, String to, String using) {
        try {

            File tempFromFile = new File("tFrom.xml");
            //File tempFromFile = File.createTempFile("tempFrom", ".xml");
           tempFromFile.deleteOnExit();

            File fromFile = new File(from);

            copy(fromFile, tempFromFile);

            //File tempUsingFile = File.createTempFile("tempUsing", ".xsl");
            File tempUsingFile = new File("tUsing.xsl");
            tempUsingFile.deleteOnExit();

            File usingFile = new File(using);

            copy(usingFile, tempUsingFile);


            // JAXP reads data using the Source interface
            Source xmlSource = new StreamSource(tempFromFile);
            Source xsltSource = new StreamSource(tempUsingFile);

            // the factory pattern supports different XSLT processors
            TransformerFactory transFact = TransformerFactory.newInstance();
            Transformer trans = transFact.newTransformer(xsltSource);

            trans.transform(xmlSource, new StreamResult(to));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void transformFSM(String from, String to) {
        transformFile(from, to, new File(EnvDescription.fsmxsl)
                .getAbsolutePath());
    }

    private static void copy(File src, File dst) throws IOException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

}
